//
//  LJFNetworkingManager.m
//  networking
//
//  Created by 刘锦锋 on 16/7/20.
//  Copyright © 2016年 com.ljf. All rights reserved.
//

#import "LJFNetworkingManager.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"

@implementation LJFNetworkingManager

+ (LJFNetworkingManager *)shareManager
{
    static LJFNetworkingManager *handler = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handler = [[LJFNetworkingManager alloc] init];
    });
    return handler;
}

/**
 *  封装的get请求
 *
 *  @param URLString  请求的链接
 *  @param parameters 请求的参数
 *  @param success    请求成功回调
 *  @param failure    请求失败回调
 */
- (void)GET:(NSString *)URLString parameters:(NSDictionary *)parameters success:(LJFAsiSuccessBlock)success failure:(LJFAsiFailureBlock)failure showHUD:(UIView *)showView
{
    if (showView)
    {
        [MBProgressHUD showHUDAddedTo:showView animated:YES];
    }
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
    NSLog(@"--请求url地址--%@\n",URLString);
    NSLog(@"----请求参数%@\n",parameters);

    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:manager.responseSerializer.acceptableContentTypes];
    [contentTypes addObject:@"text/html"];
    [contentTypes addObject:@"text/plain"];
    [contentTypes addObject:@"text/json"];
    [contentTypes addObject:@"application/json"];
    [contentTypes addObject:@"text/javascript"];
    [contentTypes addObject:@"text/xml"];
    
    manager.responseSerializer.acceptableContentTypes = contentTypes;
    manager.requestSerializer.timeoutInterval = (self.timeoutInterval ? self.timeoutInterval : 20);
    
     NSString *urlStr=[NSURL URLWithString:URLString]?URLString:[self strUTF8Encoding:URLString];
    
    [manager GET:urlStr parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress)
     {
         
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
         
         if (showView)
         {
             [MBProgressHUD hideHUDForView:showView animated:YES];
         }

         NSLog(@"--请求返回结果--%@\n",responseObject);
         
         if (success)
         {
             int code = 0;
             NSString *msg = nil;
             
             if (responseObject)
             {
                 NSString *success   = responseObject[@"code"];
                 code                = success.intValue;
                 
                 if (code == 200)
                 {
                     code = 1;
                     msg = @"请求成功";
                 }else
                 {
                     code = 0;
                     msg = responseObject[@"datas"][@"error"];
                 }
             }
             success(responseObject[@"datas"],code,msg);
         }
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
         if (failure)
         {
             failure(error);
         }
         
         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
         
         if (showView)
         {
             [MBProgressHUD hideHUDForView:showView animated:YES];
         }
     }];
}

/**
 *  封装的POST请求
 *
 *  @param URLString  请求的链接
 *  @param parameters 请求的参数
 *  @param success    请求成功回调
 *  @param failure    请求失败回调
 */
- (void)POST:(NSString *)URLString parameters:(NSDictionary *)parameters success:(LJFAsiSuccessBlock)success failure:(LJFAsiFailureBlock)failure showHUD:(UIView *)showView
{
    if (showView)
    {
        [MBProgressHUD showHUDAddedTo:showView animated:YES];
    }
     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
    NSLog(@"--请求url地址--%@\n",URLString);
    NSLog(@"----请求参数%@\n",parameters);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
//    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:manager.responseSerializer.acceptableContentTypes];
    [contentTypes addObject:@"text/html"];
    [contentTypes addObject:@"text/plain"];
    [contentTypes addObject:@"text/json"];
    [contentTypes addObject:@"application/json"];
    [contentTypes addObject:@"text/javascript"];
    [contentTypes addObject:@"text/xml"];
    
    manager.responseSerializer.acceptableContentTypes = contentTypes;
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer]
    manager.requestSerializer.timeoutInterval = (self.timeoutInterval ? self.timeoutInterval : 20);
    
    NSString *urlStr=[NSURL URLWithString:URLString]?URLString:[self strUTF8Encoding:URLString];
    
    [manager POST:urlStr parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress)
    {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
         
         if (showView)
         {
             [MBProgressHUD hideHUDForView:showView animated:YES];
         }
         
//         NSLog(@"--请求返回结果--%@\n",responseObject);
         NSData* data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
         NSString* str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
         NSLog(@"--请求返回结果--resultStr==%@",str);

         
         if (success)
         {
             int code = 0;
             NSString *msg = nil;
             
             if ([responseObject isKindOfClass:[NSDictionary class]])
             {
                 NSString *success   = responseObject[@"error_no"];
                 code                = success.intValue;
                 
                 if (code == 1 || code == 2)
                 {
                     
                     msg = responseObject[@"error_info"];
                 }else
                 {
                     
                     if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]])
                     {
                         msg = responseObject[@"error_info"];
                     }else
                     {
                          msg = responseObject[@"error_info"];
                     }
                    
                 }
                 
                 
             }
             if ([responseObject isKindOfClass:[NSArray class]]) {
                 success(responseObject,1,@"");
             }else{
             success(responseObject[@"data"],code,msg);
             }
         }
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
         
         if (failure)
         {
             failure(error);
         }
         NSLog(@"error == %@",error);
         
         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
         
         if (showView)
         {
             [MBProgressHUD hideHUDForView:showView animated:YES];
         }
     }];
}








- (void)POST:(NSString *)URLString parameters:(NSDictionary *)parameters success:(LJFAsiSuccessBlock)success failure:(LJFAsiFailureBlock)failure showHUD:(UIView *)showView andisJsonString:(NSString *)jsonstr
{
    if (showView)
    {
        [MBProgressHUD showHUDAddedTo:showView animated:YES];
    }
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
    NSLog(@"--请求url地址--%@\n",URLString);
    NSLog(@"----请求参数%@\n",parameters);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
//     manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", nil];
    NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:manager.responseSerializer.acceptableContentTypes];
    [contentTypes addObject:@"text/html"];
    [contentTypes addObject:@"text/plain"];
    [contentTypes addObject:@"text/json"];
    [contentTypes addObject:@"application/json"];
    [contentTypes addObject:@"text/javascript"];
    [contentTypes addObject:@"text/xml"];
    
    manager.responseSerializer.acceptableContentTypes = contentTypes;
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = (self.timeoutInterval ? self.timeoutInterval : 20);
    
    NSString *urlStr=[NSURL URLWithString:URLString]?URLString:[self strUTF8Encoding:URLString];
    
    [manager POST:urlStr parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress)
     {
         
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
         
         if (showView)
         {
             [MBProgressHUD hideHUDForView:showView animated:YES];
         }
         
                  NSLog(@"--请求返回结果--%@\n",responseObject);
        
         NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:0 error:nil];
         NSString* str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
         NSLog(@"--请求返回结果--resultStr==%@",str);
         
         
         if (success)
         {
             int code = 0;
             NSString *msg = nil;
             
             if (responseObject)
             {
                 NSString *success   = responseObject[@"error_no"];
                 code                = success.intValue;
                 
                 if (code == 1 || code == 2)
                 {
                     
                     msg = responseObject[@"error_info"];
                 }else
                 {
                     
                     if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]])
                     {
                         msg = responseObject[@"error_info"];
                     }else
                     {
                         msg = responseObject[@"error_info"];
                     }
                     
                 }
             }
             success(responseObject[@"data"],code,msg);
         }
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
         
         if (failure)
         {
             failure(error);
         }
         NSLog(@"error == %@",error);
         
         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
         
         if (showView)
         {
             [MBProgressHUD hideHUDForView:showView animated:YES];
         }
     }];
}











- (void)POST:(NSString *)URLString upLoadImages:(NSArray*)images parameters:(NSDictionary *)parameters success:(LJFAsiSuccessBlock)success failure:(LJFAsiFailureBlock)failure showHUD:(UIView *)showView
{
    if (showView)
    {
        [MBProgressHUD showHUDAddedTo:showView animated:YES];
    }
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
    NSLog(@"--请求url地址--%@\n",URLString);
    NSLog(@"----请求参数%@\n",parameters);
    
    NSString *urlStr=[NSURL URLWithString:URLString]?URLString:[self strUTF8Encoding:URLString];
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:mgr.responseSerializer.acceptableContentTypes];
    [contentTypes addObject:@"text/html"];
    [contentTypes addObject:@"text/plain"];
    [contentTypes addObject:@"text/json"];
    [contentTypes addObject:@"application/json"];
    [contentTypes addObject:@"text/javascript"];
    [contentTypes addObject:@"text/xml"];
    mgr.responseSerializer.acceptableContentTypes =contentTypes;
    [mgr POST:urlStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
     {
         UIImage *image ;
         NSData *data ;
      
         NSArray * cardArry = [NSArray new];
         
         for (int i = 0; i < images.count; i ++)
         {
             if ([images[i] isKindOfClass:[UIImage class]]) {
                 cardArry = images;
                 NSString * str = @"photo_album";
                 data = UIImageJPEGRepresentation(cardArry[i], 0.3);
                 NSString* date;
                 NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
                 [formatter setDateFormat:@"YYYYMMddhhmmss"];
                 date = [formatter stringFromDate:[NSDate date]];
                 int x = arc4random() % 100;
                 NSString * testname =[NSString stringWithFormat:@"%d.jpg",[date intValue]-x];
                 NSLog(@"%@",testname);
                 [formData appendPartWithFileData:data name:str fileName:testname mimeType:@"image/jpg/png"];
             }else if ([images[i] isKindOfClass:[NSData class]])
             {
                 NSData * mydata = images[i];
                 NSString * mydate;
                 NSString * str = @"onlinevideo";
                 NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
                 [formatter setDateFormat:@"YYYY.MM.dd-hh:mm:ss"];
                 mydate = [formatter stringFromDate:[NSDate date]];
                 int x = arc4random() % 100;
                 NSString * testname =[NSString stringWithFormat:@"%d.mp4",[mydate intValue]-x];
                 NSLog(@"%@",testname);
                 [formData appendPartWithFileData:mydata name:str fileName:testname mimeType:@"video/mpeg"];
             }
             else if([images[i][@"pic"] isKindOfClass:[NSArray class]] ) {
                 cardArry = images[i][@"pic"];
                 NSString *str = [NSString stringWithFormat:@"%@",images[i][@"imgname"]];
                 
                 for (int j=0; j<cardArry.count; j++) {
                      data = UIImageJPEGRepresentation(cardArry[j], 0.3);
                     NSString* date;
                     NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
                     [formatter setDateFormat:@"YYYYMMddhhmmss"];
                     date = [formatter stringFromDate:[NSDate date]];
                     int x = arc4random() % 100;
                     
                     NSString * testname =[NSString stringWithFormat:@"%d.jpg",[date intValue]-x];
                     NSLog(@"%@",testname);
                     [formData appendPartWithFileData:data name:str fileName:testname mimeType:@"image/jpg/png"];
                 }
             }
             
             else{
                 image = images[i][@"pic"];
                 data = UIImageJPEGRepresentation(image, 0.3);
                 NSString *str = [NSString stringWithFormat:@"%@",images[i][@"imgname"]];
                 NSString* date;
                 NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
                 [formatter setDateFormat:@"YYYYMMddhhmmss"];
                 date = [formatter stringFromDate:[NSDate date]];
                 int x = arc4random() % 100;
                 
                 NSString * testname =[NSString stringWithFormat:@"%d.jpg",[date intValue]-x];
                 NSLog(@"%@",testname);
                 [formData appendPartWithFileData:data name:str fileName:testname mimeType:@"image/jpg/png"];
             }
            
            
         }
         
     } progress:^(NSProgress * _Nonnull uploadProgress)
     {
         
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
         
         if (showView)
         {
             [MBProgressHUD hideHUDForView:showView animated:YES];
         }
         
         NSLog(@"--请求返回结果--%@\n",responseObject);
         NSData* data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
         NSString* str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
         NSLog(@"--请求返回结果--resultStr==%@",str);
         
         if (success)
         {
             int code = 0;
             NSString *msg = nil;
             
             if (responseObject)
             {
                 NSString *success   = responseObject[@"error_no"];
                 code                = success.intValue;
                 
                 if (code == 1 || code == 409)
                 {
                     //code = 1;
                     msg = @"请求成功";
                 }else
                 {
                     //code = 0;
                     msg = responseObject[@"error_info"];
                 }
             }
             success(responseObject[@"data"],code,msg);
         }
         
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
         if (failure)
         {
             failure(error);
         }
         NSLog(@"error == %@",error);
         
         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
         
         if (showView)
         {
             [MBProgressHUD hideHUDForView:showView animated:YES];
         }
         
     }];
}

-(NSString *)strUTF8Encoding:(NSString *)str
{
    return [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

@end
